package com.xxl.job.admin.core.alarm.impl;

import cn.hutool.http.HttpUtil;
import com.google.gson.JsonObject;
import com.xxl.job.admin.core.alarm.JobAlarm;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.model.XxlJobLog;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class DingTalkAlarm implements JobAlarm {

    private static final Logger log = LoggerFactory.getLogger(DingTalkAlarm.class);

    private static final String DING_TALK_ROBOT_URL = "https://oapi.dingtalk.com/robot/send?access_token=%s";

    @Override
    public boolean doAlarm(XxlJobInfo info, XxlJobLog jobLog) {
        String dingTalkRobotKey = System.getenv("DING_TALK_ROBOT_KEY");
        if (Strings.isEmpty(dingTalkRobotKey)) {
            return false;
        }
        try {
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("msgtype", "text");
            JsonObject text = new JsonObject();
            String handleMsg = jobLog.getHandleMsg();
            handleMsg = handleMsg == null ? "" : handleMsg.length() > 3000 ? handleMsg.substring(0, 3000) : handleMsg;
            text.addProperty("content", String.format("%s\r\n定时任务执行失败:%s\r\n调度器异常:%s\r\n执行器异常:%s",
                    System.getenv("PROJECT_NAME"), info.getJobDesc(),
                    jobLog.getTriggerMsg(),
                    handleMsg));
            jsonObject.add("text", text);

            String post = HttpUtil.post(String.format(DING_TALK_ROBOT_URL, dingTalkRobotKey),
                    jsonObject.toString());
            log.info("钉钉消息{} 发送成功:{}", jsonObject, post);
            return true;
        } catch (Exception e) {
            log.error("钉钉消息 发送异常]", e);
        }
        return false;
    }
}
